/**
 * 用于(项目/产品)各自单独自定义的js工具类
 **/
var mytools = {};
mytools.skin_admin_flag=true;//是否开启后台切换主题功能：注意top内<aside class="control-sidebar control-sidebar-dark">标签组
mytools.skin_admin_key="_iussoft_skin_project_console";//自定义存储主题key标识

/**
 * 清空数据，按照样式清空；
 * 1）按照form表单Id清空：id参数#开头
 * 2）按照form表单class样式清空：id参数.开头
 */
mytools.cleanData=function(id){
	$(id).find(".clean").val("");
	$(id).find("IMG").each(function(){
		$(this).attr("src",strUtil.doNull($(this).attr("data-def"), ctx+"/images/def.jpg"));
		//$(this).next().text("选择主图");
		$(this).siblings("label").eq(2).text("");
		$(this).siblings("a").text("");
	});
}
//删除行
mytools.delRows=function(obj){
    $(obj).parent().parent().remove();
}
/**
 *
    json数据格式化展示
    <pre style="height: 260px; overflow-y: scroll;"><code id="viewForm1_resp_msg_form_json"></code></pre>
    mytools.showViewByJson(codeId,myData.entity);
 */
mytools.showViewByJson=function (id,data){
    // var data ={"name":"张三","age":25,"color":"#ffa500","gender":"男","location":{"city":"北京","dist":"海淀区","other":{"user":"test","ab":10}},"family":[{"name":"孩子1","age":"10"},{"name":"孩子2","age":"20"}]};
    var code_json = document.querySelector('#'+id);
    // console.log(code_json.tagName,"code_json");
    if("TEXTAREA"==code_json.tagName){
        $('#'+id).val('');
        $('#'+id).val(JSON.stringify(data, null,4));
    }else{
        $('#'+id).text('');
        code_json.textContent = JSON.stringify(data, null,4);
    }
};
//xml格式化工具
mytools.showXmlFormat=function (id,data,prefix){
    $('#'+id).text('');
    //判断是否默认了前缀版本号和编码
    var start_prefix = (prefix==undefined||prefix=='')?'<?xml version="1.0" encoding="UTF-8"?>':prefix;
    //获取原始根目录name
    var srcRootTagName = $($.parseXML(data)).find("*").eq(0).prop("tagName").toLowerCase();
    //转换json后，在回转xml指定根节点名称
    var xmlNewStr = $.json2xml($.xml2json(data),{'rootTagName':srcRootTagName});
    //拼接开始内容
    var resXml=start_prefix+'\n'+xmlNewStr;

    $('#'+id).text(resXml);
}
/**
 * 清空校验规则提示信息，按照样式清空；
 * 1）按照form表单Id清空：id参数#开头
 * 2）按照form表单class样式清空：id参数.开头
 */
mytools.cleanValidate=function(id){
	var validate = $(id).data('bootstrapValidator').validate();
	validate.resetForm();
}
/**
 * 关闭模态窗口
 */
mytools.closeModal=function(id){
	$('#'+id).modal('hide');
}

/**
 * 封装的pjax跳转方法1
 */
mytools.pjax=function(url,container,fragment){
	var defcon = ".content-wrapper";
	var a=defcon;
	var b=defcon;
	if(container!=undefined &&container!=null && container!=''){
		a = container;
	}
	if(fragment!=undefined &&fragment!=null && fragment!=''){
		b = fragment;
	}
	//alert(url+"  "+a+"  "+b);
	 $.pjax({  
         url: url,  
         container: a,  
         fragment: b,
         cache: false,
         //maxCacheLength:0,
         timeout: 8000
       })
}
/**
 * 封装的load跳转方法 常用按钮跳转
 */
mytools.load=function(url){
	var histClick = clickMenu;
	$.ajaxSetup ({cache: false});
	$(".content-wrapper").load(url+" .content-wrapper>",function(resultData){
		 $result = $(resultData);
        $result.find("script").appendTo(".content-wrapper");//保证子页面的js内容能被引入进来
        clickMenu = histClick;
        showClickMenu();
	});
}
$(function () {
    if(mytools.skin_admin_flag){
        //开启状态，获取最新缓存的值
        console.log(mytools.skin_admin_key,mytools.skin_admin_flag);
        var bodyObj = $("body");
        var skinOldClass = strUtil.getClassNameByFix("skin-",bodyObj.attr("class"));
        var skin_storage_value = strUtil.doNull(strUtil.getLocalStorage(mytools.skin_admin_key),skinOldClass);
        bodyObj.removeClass(skinOldClass).addClass(skin_storage_value);
    }
})



//计算bootstrapTable首次初始化显示的页码数
mytools.getCountShowPageSize=function (searcBoxId) {
    var first_rows = 10;
    var box_search_form_height = 0;
    if(!isNull(searcBoxId)){
        box_search_form_height = Math.ceil($(searcBoxId).outerHeight(true));
    }
    var win_height = $(window).height();
    var other_height = 320;//其他高度（底部+表头+其他微调空格）
    var table_tbody_max_height = win_height - box_search_form_height - other_height;
    var trHeight = 40;
    if(table_tbody_max_height>trHeight){
        first_rows = Math.floor(table_tbody_max_height/trHeight);
    }
    console.log("mytools.initBootstrapTable.getCountShowPageSize->","window_height="+win_height+",box_search_form_height="+box_search_form_height+",table_tbody_max_height="+table_tbody_max_height+",first_rows="+first_rows);
    return first_rows;
}
mytools.initBootstrapTable=function (config) {
    var configJson = {
        url : doNull(config.url,''),
        searcBoxId : doNull(config.searcBoxId,''),
        exportFileName : doNull(config.exportFileName,'数据导出')
    };
    console.log("mytools.initBootstrapTable.config->",configJson);
    var searchFormId = $(configJson.searcBoxId).find("form").attr("id");
    $table.bootstrapTable({
        url:configJson.url,
        // pageSize:mytools.getCountShowPageSize(configJson.searcBoxId),//【个性需求】自定义根据页面窗口高度重写计算高度方法
        sidePagination:"server",
        queryParamsType:'undefined',//采用服务端分页方式为此值
        queryParams:function (params) {//请求服务器数据参数
            //当sidePagination="server"时此值设置为undefined可以获取pageNumber，pageSize，searchText，sortName，sortOrder
            //默认是设置为limit可以获取limit, offset, search, sort, order
            console.log("mytools.bootstrapTable.params.old->",params);
            // $("#"+searchFormId).find("input[name='cateEname']").val(params.searchText);
            var param =  FormUtil.serializeJson("#"+searchFormId);
            param["page"]=params.pageNumber;
            param["rows"]=params.pageSize;
            var sortName = params.sortName;
            if(!isNull(params.sortName)){
                var sort_objname = sortName.split(".")[0];
                var sort_filed = sortName.split(".")[1];
                sort_filed=sort_filed.replace(/\B([A-Z])/g, '_$1').toLowerCase();//驼峰转下划线
                param["orderBy"]=sort_objname+'.'+sort_filed+' '+params.sortOrder;
            }
            console.log("mytools.bootstrapTable.params->",param);
            return param;
        },
        exportDataType: "all", //basic', 'all', 'selected'.
        exportOptions:{
            ignoreColumn: [0],//导出时忽略第一列
            fileName:configJson.exportFileName
        },
        exportTypes:['excel','json','txt','csv'],//导出类型
        // rowStyle: function (row, index) {
        //     var classesArr = ['success', 'info'];
        //     var strclass = "";
        //     if (index % 2 === 0) {//偶数行
        //         strclass = classesArr[0];
        //     } else {//奇数行
        //         strclass = classesArr[1];
        //     }
        //     return { classes: strclass };
        // },//隔行变色,
        onLoadSuccess: function(data){//加载成功时执行
            console.log("mytools.bootstrapTable.onLoadSuccess",data);
        },
        onLoadError: function(status){//加载失败时执行
            console.log("mytools.bootstrapTable.onLoadError",status);
        },
        onRefresh: function(param){//加载失败时执行
            console.log("mytools.bootstrapTable.onRefresh",param);
        }
    });
}
//获取序号
mytools.funPageNumber = function(value, row, index) {
    //获取每页显示的数量
    var pageSize=$table.bootstrapTable('getOptions').pageSize;
    //获取当前是第几页
    var pageNumber=$table.bootstrapTable('getOptions').pageNumber;
    //返回序号，注意index是从0开始的，所以要加上1
    return pageSize * (pageNumber - 1) + index + 1;
}


//新增test数据源方法，配置默认jdb连接数据的配置
var DataBaseTypeMap = {};
DataBaseTypeMap["mysql"] = {
    "driverClassName": "com.mysql.jdbc.Driver",
    "jdbcUrl": "jdbc:mysql://39.104.104.181:3306/test?useUnicode=true&characterEncoding=UTF8&allowMultiQueries=true&useSSL=false",
    "jdbcUsername": "ius_base",
    "jdbcPassword": "ius_base2018"
};
DataBaseTypeMap["oracle"] = {
    "driverClassName": "oracle.jdbc.OracleDriver",
    "jdbcUrl": "jdbc\:oracle\:thin\:@127.0.0.1\:1521\:orcl",
    "jdbcUsername": "test",
    "jdbcPassword": "test_2018"
};
mytools.addTestDatasource =function (databaseType,sysEname) {
    var msg_load = layer.msg("正在配置默认数据源，请耐心等待...");
    var paramData = {};
    paramData["pageName"]="datasource-list";
    paramData["formName"]="addForm";
    paramData["tRpcDatasource.sysEname"]=sysEname;
    paramData["tRpcDatasource.dataName"]=sysEname;
    paramData["tRpcDatasource.databaseType"]=databaseType;

    var jdbcObj = DataBaseTypeMap[databaseType];
    paramData["tRpcDatasource.jdbcUrl"]=jdbcObj["jdbcUrl"];
    paramData["tRpcDatasource.driverClassName"]=jdbcObj["driverClassName"];
    paramData["tRpcDatasource.jdbcUsername"]=jdbcObj["jdbcUsername"];
    paramData["tRpcDatasource.jdbcPassword"]=jdbcObj["jdbcPassword"];
    $.ajax({
        type:"post",url:common_submit_url,data: paramData,dataType:"json",async:false,
        success: function(myData){
            console.log("mytools.addTestDatasource",myData);
            if(myData.flag=="T"){
                mytools.loadCacheDatasource(sysEname);
                layer.msg("数据源添加成功，您可以开始设计表了！");
                layer.close(msg_load);
            }else{
                layer.alert("数据源添加失败！");
            }
        }
    });
}
//刷新数据源缓存
mytools.loadCacheDatasource =function (sysEname) {
    var index_load = layer.msg("正在同步缓存");
    $.ajax({ type:'post',dataType:'json',
        url: common_cache_url+"init",
        //url:"${ctx}/info/loadDatasource",
        data:{"pageName":"datasource-list","formName":"initiCacheForm","tRpcDatasource.w_sysEname":sysEname},
        success: function(myData){
            layer.close(index_load);
            console.log("mytools.loadCacheDatasource",myData);
        }
    });
}
//刷新网关路由配置缓存
mytools.loadCacheZuulRoute=function(){
    var index_load = layer.load(1, {shade: false});
    $.ajax({
        type: 'post',
        url: common_cache_url+"init",
        data:{"pageName":"sys-zuul-route","formName":"initiCacheForm","sysZuulRoute.w_enabled":"1"},
        dataType: 'json',
        success: function (myData) {
            layer.close(index_load);
            console.log("mytools.loadCacheZuulRoute",myData);
        }
    });
}

/**
 判断form表单中某字段输入值是否已重复（调用后台）
 1、需要判重的文本框添加下面事件和属性
 onblur="mytools.validFieldRepeat(this)"
 data-validate-repeat-message="此登录账号已存在，请更换！"  //发现重复提示的文字
 2、修改时文本框需多配置下面这个属性。其值是editForm表单存业务主键的隐藏域name值
 data-validate-repeat-selfname="ssInsurPro.w_infoId"
 */
mytools.validFieldRepeat=function(obj){
    var thisObj = $(obj);
    var thisVal = thisObj.val();
    if(strUtil.isNull(thisVal)){
        return;
    }
    var fieldName = thisObj.attr("name");
    if(strUtil.isNull(fieldName)||fieldName.indexOf('.')<0){
        layer.msg('name属性配置不合法');
        return;
    }
    var formId = thisObj.parents("form").eq(0).attr("id");//获取当前元素所在父层级中的就近的formId
    if(strUtil.isNull(formId)<0){
        layer.msg(fieldName+'元素必须存放form表单内！');
        return;
    }
    console.log('formId->'+formId);
    var formObj =  $("#"+formId);
    var form_pageName = formObj.find("input[name='pageName']").val();
    var form_formName = formObj.find("input[name='formName']").val();
    var isEdit = false;//标记是否是修改表单
    if(form_formName=='editForm'){
        isEdit = true;
    }
    var fieldArr = fieldName.split(".");
    var objName = fieldArr[0];
    var condisStr = objName+".w_"+fieldArr[1];
    var pageName = strUtil.doNull(thisObj.attr("data-validate-repeat-page-name"),form_pageName);
    var formName = strUtil.doNull(thisObj.attr("data-validate-repeat-form-name"),'searchForm');
    var objMsg = strUtil.doNull(thisObj.attr("data-validate-repeat-message"),"此项输入的值已重复，请更换！");
    var isClean = strUtil.doNull(thisObj.attr("data-validate-repeat-clean"),'true');
    console.log('valid.req',pageName+'='+pageName+'&'+formName+'='+formName+'&'+condisStr+'='+thisVal);
    var selfInput = thisObj.attr("data-validate-repeat-selfname");
    var editRemoveId_name = '',editRemoveId_val='';
    if(isEdit){
        if(strUtil.isNull(selfInput)){
            layer.msg(formId+'下'+fieldName+'必须设置属性：data-validate-repeat-selfname');
            return;
        }
        var selfInputObj = formObj.find("input[name='"+selfInput+"']");
        if(!selfInputObj || strUtil.isNull(selfInputObj.val())){
            layer.msg(formId+"下"+fieldName+"input[name='"+selfInput+"']元素不存在或值为空！");
            return;
        }
        editRemoveId_name =selfInput.split('w_')[1];
        editRemoveId_val = selfInputObj.val();
        console.log('valid.type','edit->'+editRemoveId_name+'='+editRemoveId_val);
    }else{
        console.log('valid.type','add');
    }
    var index_load = layer.load(1, {shade: false});
    var paramLoadData = {};
    paramLoadData['pageName']=pageName;
    paramLoadData['formName']=formName;
    paramLoadData[condisStr]=thisVal;
    $.getJSON(common_list_url,paramLoadData, function(myData2){
        console.log('valid.res',myData2);
        layer.close(index_load);
        if(myData2.total>0){
            if(isEdit){
                //修改情况下，排除自己判断（自己改自己）
                var oldInfoIdVal = myData2.rows[0][objName][editRemoveId_name];
                if(editRemoveId_val==oldInfoIdVal){
                    return;
                }
            }
            console.log('valid.msg'+objMsg);
            layer.msg(objMsg);
            if(isClean=='true'){
                thisObj.val('');
                formObj.data('bootstrapValidator').updateStatus(fieldName,'NOT_VALIDATED',null).validateField(fieldName);
            }
        }
    });
}
